﻿<%@ WebHandler Language="C#" Class="UpAgAttachHandler" %>

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Collections;
using System.Globalization;
using System.Web;
using System.IO;
using LitJson;
using System.Web.SessionState;
using System.Drawing;
using System.Drawing.Imaging;
using Util.BasePage;
using RichECMS;

/// <summary>
/// 协议附件上传后台处理程序
/// </summary>
public class UpAgAttachHandler : Util.BasePage.BasePage, IHttpHandler, IRequiresSessionState
{
    //文件保存目录路径
    private String savePath = DateTime.Now.ToString("yyyyMMdd") + "\\";
    //缩略图文件保存目录路径
    private String savePathmini =DateTime.Now.ToString("yyyyMMdd") + "\\";
    //文件保存目录URL
    private String saveUrl =  DateTime.Now.ToString("yyyyMMdd") + "/";
    //定义允许上传的文件扩展名
    private String fileTypes = "gif,jpg,jpeg,png,bmp,rar,zip,flv,swf";
    //最大文件大小
    private int maxSize = 10000000;

    private HttpContext context;
    public void ProcessRequest(HttpContext context)
    {
        this.context = context;

        if (State.LoginUser.IssuePath == null || State.LoginUser.VartualPath == null)
        {
            context.Response.Write("请登陆后台后进行操作");
            return;
        }
        
        HttpPostedFile imgFile = context.Request.Files["imgFile"];
        if (imgFile == null)
        {
            ShowError("请选择文件。");
        }

        String dirPath = context.Server.MapPath("~/") + "news\\" + State.LoginUser.VartualPath + "\\Pcfiles\\" + savePath;
        String dirPathmini = context.Server.MapPath("~/") + "news\\" + State.LoginUser.VartualPath + "\\Pcfiles\\" + savePathmini;
        if (!Directory.Exists(dirPath))
        {
            Directory.CreateDirectory(dirPath);
        }
        if (!Directory.Exists(dirPathmini))
        {
            Directory.CreateDirectory(dirPathmini);
        }

        String fileName = imgFile.FileName.Trim();
        String fileExt = Path.GetExtension(fileName).ToLower();
        ArrayList fileTypeList = ArrayList.Adapter(fileTypes.Split(','));

        if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
        {
            ShowError("上传文件大小超过限制。");
        }

        if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1)
        {
            ShowError("上传文件扩展名是不允许的扩展名。");
        }

        //if (HandleImg.IsImage(imgFile) != "true")
        //{
        //    ShowError("上传文件内容不是图片,请上传图片");
        //}

		string strTime = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo);
        String newFileName =strTime + fileExt;
        String filePath = dirPath + newFileName;
        imgFile.SaveAs(filePath);
		
		if (IsImage(imgFile) == "true")
		{
			string	strMiniImgName = strTime +  "mini" + fileExt;
			String minifilePath = dirPath + strMiniImgName;
			//生成缩略图
			KiResizeImage(filePath, minifilePath, 430, 430, 1);
		}
		
        ////String filePathmini = dirPathmini + "mini" + newFileName;

        ////Image imgtemp = Image.FromStream(imgFile.InputStream);
        ////imgtemp.Save(filePath);
        ////imgtemp.Dispose();
        ////处理图片，过滤有害代码
        //MemoryStream memostr = new MemoryStream();
        //Image imgtemp = Image.FromStream(imgFile.InputStream);
        //imgtemp.Save(memostr, ImageFormat.Png);
        //imgtemp = Image.FromStream(memostr);
        //imgtemp.Save(filePath, ImageFormat.Jpeg);
        //imgtemp.Dispose();

        //生成缩略图

        //String fileUrl = saveUrl + newFileName;
        //CreateResourceBasedLiteralControl()
        //HandleImg.KiResizeImage(filePath, filePathmini, 150, 150, 1);

        Hashtable hash = new Hashtable();
        hash["error"] = 0;
        hash["url"] = "/news/" + State.LoginUser.VartualPath + "/Pcfiles/" + saveUrl + newFileName;
        context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
        context.Response.Write(JsonMapper.ToJson(hash));
        context.Response.End();
    }

    private void ShowError(string message)
    {
        Hashtable hash = new Hashtable();
        hash["error"] = 1;
        hash["message"] = message;
        context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
        context.Response.Write(JsonMapper.ToJson(hash));
        context.Response.End();
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
	
	 #region

    public static bool ImgWidthBiggerThenHeight(string url)
    {
        Image img = Image.FromFile(url);
        try
        {
            if (img.Width >= img.Height)
            {
                img.Dispose();
                return true;
            }
            else
            {
                img.Dispose();
                return false;
            }

        }
        catch (Exception imgerror)
        {
            return false;
        }
    }

    public static string IsImage(HttpPostedFile postfile)
    {
        try
        {
            using (Image img = Image.FromStream(postfile.InputStream))
            {
                MemoryStream memoimg = new MemoryStream();
                img.Save(memoimg, ImageFormat.Jpeg);
                img.Dispose();
                return "true";
            }
        }
        catch (Exception)
        {
            return "false";
        }

        //var img = Image.FromStream(postfile.InputStream);
        //var memoimg = new MemoryStream();
        //try
        //{
        //    img.Save(memoimg, ImageFormat.Jpeg);
        //    img.Dispose();
        //    return "true";
        //}
        //catch (Exception imgerror)
        //{
        //    return imgerror.Message;
        //}
        //finally
        //{
        //    memoimg.Dispose();
        //}
    }

    public static bool IsImageByUploadFile(HttpPostedFile postfile)
    {
        try
        {
            //var fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            BinaryReader reader = new BinaryReader(postfile.InputStream);
            byte[] b = new byte[2];
            byte buffer = reader.ReadByte();
            b[0] = buffer;
            string fileClass = buffer.ToString();
            buffer = reader.ReadByte();
            b[1] = buffer;
            fileClass += buffer.ToString();


            reader.Close();
            //fs.Close();
            if (fileClass == "255216" || fileClass == "7173" || fileClass == "6677" || fileClass == "13780")//255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar 
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        catch
        {
            return false;
        }

        //var img = Image.FromStream(postfile.InputStream);
        //var memoimg = new MemoryStream();
        //try
        //{
        //    img.Save(memoimg, ImageFormat.Jpeg);
        //    img.Dispose();
        //    return "true";
        //}
        //catch (Exception imgerror)
        //{
        //    return imgerror.Message;
        //}
        //finally
        //{
        //    memoimg.Dispose();
        //}
    }

    public static bool IsImage(string path)
    {
        try
        {
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            BinaryReader reader = new BinaryReader(fs);
            byte[] b = new byte[2];
            byte buffer = reader.ReadByte();
            b[0] = buffer;
            string fileClass = buffer.ToString();
            buffer = reader.ReadByte();
            b[1] = buffer;
            fileClass += buffer.ToString();


            reader.Close();
            fs.Close();
            if (fileClass == "255216" || fileClass == "7173" || fileClass == "6677" || fileClass == "13780")//255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar 
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        catch
        {
            return false;
        }
    }

    #endregion

    #region 绘制缩略图

    /// <summary>
    /// Resize图片
    /// </summary>
    /// <param name="bmp">原始Bitmap</param>
    /// <param name="newW">新的宽度</param>
    /// <param name="newH">新的高度</param>
    /// <param name="mode">保留着，暂时未用</param>
    /// <returns>处理以后的图片</returns>
    private static Bitmap KiResizeImage(Bitmap bmp, int newW, int newH, int mode)
    {
        Bitmap b = new Bitmap(newW, newH);
        try
        {
            Graphics g = Graphics.FromImage(b);
            // 插值算法的质量
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            // 高质量
            g.SmoothingMode = SmoothingMode.HighQuality;

            g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
            g.Dispose();
            return b;
        }
        catch
        {
            return null;
        }
        //finally
        //{
        //    b.Dispose();
        //}
    }

    /// <summary>
    ///  缩放
    /// </summary>
    /// <param name="imageUrl"></param>
    /// <param name="savePath"></param>
    /// <param name="newW"></param>
    /// <param name="newH"></param>
    /// <param name="mode"></param>
    /// <returns></returns>
    public static void KiResizeImage(string imageUrl, string savePath, int newW, int newH, int mode)
    {
        Image image = System.Drawing.Image.FromFile(imageUrl);

        int tHeight = 0;
        int tWidth = 0;

        //按比例计算出缩略图的宽度和高度
        if (image.Width >= image.Height)
        {
            if (newW < image.Width)
            {
                tHeight = (int)Math.Floor(Convert.ToDouble(image.Height) * (Convert.ToDouble(newW)
                / Convert.ToDouble(image.Width)));
                tWidth = newW;
            }
            else
            {
                tHeight = image.Height;
                tWidth = image.Width;
            }
        }
        else
        {
            if (newH < image.Height)
            {
                tWidth = (int)Math.Floor(Convert.ToDouble(image.Width) * (Convert.ToDouble(newH)
                / Convert.ToDouble(image.Height)));
                tHeight = newH;
            }
            else
            {
                tHeight = image.Height;
                tWidth = image.Width;
            }
        }

        Bitmap nbm = new Bitmap(image, image.Width, image.Height);
        try
        {
            image = KiResizeImage(nbm, tWidth, tHeight, mode);
            if (File.Exists(savePath))
                File.Delete(savePath);
            image.Save(savePath, ImageFormat.Jpeg);
        }
        catch
        {
            throw;
        }
    }

    public static void KiResizeImage(Image image, string savePath, int newW, int newH, int mode)
    {
        int tHeight = 0;
        int tWidth = 0;

        //按比例计算出缩略图的宽度和高度
        if (image.Width >= image.Height)
        {
            if (newW < image.Width)
            {
                tHeight = (int)Math.Floor(Convert.ToDouble(image.Height) * (Convert.ToDouble(newW)
                / Convert.ToDouble(image.Width)));
                tWidth = newW;
            }
            else
            {
                tHeight = image.Height;
                tWidth = image.Width;
            }
        }
        else
        {
            if (newH > image.Height)
            {
                tWidth = (int)Math.Floor(Convert.ToDouble(image.Width) * (Convert.ToDouble(newH)
                / Convert.ToDouble(image.Height)));
                tHeight = newH;
            }
            else
            {
                tHeight = image.Height;
                tWidth = image.Width;
            }
        }

        Bitmap nbm = new Bitmap(image, image.Width, image.Height);
        try
        {
            image = KiResizeImage(nbm, tWidth, tHeight, mode);
            if (File.Exists(savePath))
                File.Delete(savePath);
            image.Save(savePath, ImageFormat.Jpeg);
        }
        catch
        {
            throw;
        }
    }

    #endregion

}